<?php

namespace app\common\model;

use think\Db;
use think\Model;

class GoodsOrderCounter extends Model
{
    protected $name = 'goods_order_counter';


    /**
     * Notes: 获取桌号
     * User: chenLei
     * Date: 8/6/25
     * @param $shop_id
     * @return string
     */
    public static function generate($shop_id)
    {
        $today = date('Y-m-d');

        // 开启事务
        Db::startTrans();
        try {
            // 查找或创建今天的计数器
            $counter = self::where('date', $today)->where('shop_id', $shop_id)
                ->lock(true)
                ->find();

            if (!$counter) {
                // 如果不存在，创建新的计数器
                $count = 1;
                self::insert([
                    'date' => $today,
                    'shop_id' => $shop_id,
                    'count' => $count
                ]);
            } else {
                // 如果存在，计数器+1
                $count = $counter['count'] + 1;
                self::where('date', $today)
                    ->where('shop_id', $shop_id)
                    ->update(['count' => $count]);
            }

            Db::commit();

            // 生成订单编号
            $number = str_pad($count % 1000, 3, '0', STR_PAD_LEFT);

        } catch (\Exception $e) {
            Db::rollback();
            explode($e->getMessage());
        }
        return $number;
    }
}